package com.xmy.cultivate.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.request.BookClassTypeCountRs;
import com.xmy.cultivate.entity.request.BookSchoolCountRs;
import com.xmy.cultivate.entity.request.BookSchoolRs;
import com.xmy.cultivate.entity.views.SelectStudent;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 教材订购管理 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-01-04
 */
@RestController
@RequestMapping("/api/bookOrder")
@Scope("prototype")
public class BookOrderController extends BaseController {

    @Autowired
    IBookOrderService iBookOrderService;

    @Autowired
    IBookStudentService iBookStudentService;

    @Autowired
    IBookStudentAdjustService iBookStudentAdjustService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    IBookGrantInfoService iBookGrantInfoService;

    @Autowired
    ICourseTypeService iCourseTypeService;

    @Autowired
    IBookTextService iBookTextService;


    /**
     * 获取需订购列表
     *
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param classTypeId
     * @param lessonType
     * @return
     */
    @GetMapping("/getOrderSchool")
    public Result getOrderSchool(@RequestParam(name = "pageNum", defaultValue = "-1") Integer pageNum,
                                 @RequestParam(name = "pageSize", defaultValue = "-1") Integer pageSize,
                                 @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                 @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                 @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                 @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeId,
                                 @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                 @RequestParam(value = "lessonType", required = false, defaultValue = "1") Integer lessonType,
                                 @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                 @RequestParam(value = "teacherName", required = false) String teacherName,
                                 @RequestParam(value = "studentName", required = false) String studentName,
                                 @RequestParam(value = "teacherId", required = false) Long teacherId,
                                 @RequestParam(value = "schoolId", required = false) Long schoolId,
                                 @RequestParam(value = "gradeId", required = false) Long gradeId,
                                 @RequestParam(value = "yearClassId", required = false) Integer yearClassId,
                                 @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                                 @RequestParam(value = "isDetails", required = false, defaultValue = "0") Integer isDetails // 0列表，1老师详情，2学员详情
    ) {
        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        Page<BookSchoolRs> page = new Page<>(pageNum, pageSize);
        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";

        iBookOrderService.getOrderSchool(page, yearPart, quarterNum, subjectsId, classTypeId, lessonType, schoolIds, bookTextId, bookTextType, isDetails, teacherId, schoolId, yearClassId, teacherName, studentName, lessonNum, gradeId, subscribeType);

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
    }

    //需订购数量
    @GetMapping("/getOrderSchoolCountForClassType")
    public Result getOrderSchoolCountForClassType(@RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                                  @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                                  @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                                  @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeId,
                                                  @RequestParam(value = "lessonType", required = false, defaultValue = "1") Integer lessonType,
                                                  @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                                  @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                                  @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                                                  @RequestParam(value = "isDetails", required = false, defaultValue = "0") Integer isDetails // 是否为详情，0否1是
    ) {

        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        List<BookClassTypeCountRs> bookClassTypeCountRsList = iBookOrderService.getOrderSchoolCountForClassType(yearPart, quarterNum, subjectsId, classTypeId, lessonType, bookTextId, bookTextType, lessonNum, isDetails, subscribeType);
        return new Result(Code.OK, bookClassTypeCountRsList, Code.OK_MSG);
    }

    @GetMapping("/exportOrderSchool")
    @ApiOperation("未订购")
    public Result exportOrderSchool(@RequestParam(name = "pageNum", defaultValue = "-1") Integer pageNum,
                                    @RequestParam(name = "pageSize", defaultValue = "-1") Integer pageSize,
                                    @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                    @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                    @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                    @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeId,
                                    @RequestParam(value = "lessonType", required = false, defaultValue = "1") Integer lessonType,
                                    @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                    @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                    @RequestParam(value = "teacherName", required = false) String teacherName,
                                    @RequestParam(value = "studentName", required = false) String studentName,
                                    @RequestParam(value = "teacherId", required = false) Long teacherId,
                                    @RequestParam(value = "gradeId", required = false) Long gradeId,
                                    @RequestParam(value = "schoolId", required = false) Long schoolId,
                                    @RequestParam(value = "yearClassId", required = false) Integer yearClassId,
                                    @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                                    @RequestParam(value = "isDetails", required = false, defaultValue = "0") Integer isDetails // 0列表，1老师详情，2学员详情
    ) throws IOException {


        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        Page<BookSchoolRs> page = new Page<>(pageNum, pageSize);
        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";
        List<BookSchoolRs> bookSchoolRs = iBookOrderService.getOrderSchool(page, yearPart, quarterNum, subjectsId, classTypeId, lessonType, schoolIds, bookTextId, bookTextType, isDetails, teacherId, schoolId, yearClassId, teacherName, studentName, lessonNum, gradeId, subscribeType).getRecords();

        // 定义年级列表
        List<String> gradeNames = Arrays.asList(
                "幼儿园", "一年级", "二年级", "三年级", "四年级", "五年级", "六年级",
                "初一", "初二", "初三", "高一", "高二", "高三"
        );

        Map<String, Map<String, Integer>> schoolGradeData = new HashMap<>();
        for (BookSchoolRs bookSchool : bookSchoolRs) {
            Map<String, Integer> gradeData = new HashMap<>();
            for (String gradeName : gradeNames) {
                gradeData.put(gradeName, null);
            }
            for (BookSchoolCountRs bookSchoolCountRs : bookSchool.getBookCountList()) {
                int rsYearClassId = bookSchoolCountRs.getYearClassId();
                String gradeName = CommonUtil.getYearClassNameForId(rsYearClassId);
                if (gradeName != null) {
                    gradeData.put(gradeName, bookSchoolCountRs.getCount());
                }
            }
            schoolGradeData.put(bookSchool.getSchoolName(), gradeData);
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("未订购");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        List<String> headList = new ArrayList<>();
        headList.add("校区");
        headList.add("科目");
        headList.add("班型");
        headList.addAll(gradeNames);
        headList.add("合计");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引
        for (BookSchoolRs bookSchool : bookSchoolRs) {
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(bookSchool.getSchoolName());
            sheet.setColumnWidth(0, 15 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(bookSchool.getSubjectsName());
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            if (bookSchool.getClassTypeId() != null) {
                Cell cell3 = row.createCell(2);
                cell3.setCellValue(bookSchool.getClassTypeName());
                sheet.setColumnWidth(2, 15 * 256);
                cell3.setCellStyle(cellStyle);
            }

            int total = 0;
            for (int i = 0; i < gradeNames.size(); i++) {
                Cell cell = row.createCell(i + 3);
                Map<String, Integer> gradeData = schoolGradeData.get(bookSchool.getSchoolName());
                Integer count = gradeData != null ? gradeData.get(gradeNames.get(i)) : null;
                if (count != null) {
                    cell.setCellValue(count);
                    total += count;
                } else {
                    cell.setCellValue("");
                }
           /*     if (gradeData != null) {
                    Integer count = gradeData.get(gradeNames.get(i));
                    cell.setCellValue(count);
                    total += count;
                } else {
                    cell.setCellValue("");
                }*/
                sheet.setColumnWidth(i + 3, 15 * 256);
                cell.setCellStyle(cellStyle);
            }

            Cell cell4 = row.createCell(gradeNames.size() + 3);
            cell4.setCellValue(bookSchool.getCount());
            sheet.setColumnWidth(gradeNames.size() + 3, 15 * 256);
            cell4.setCellStyle(cellStyle);

        }
        String fileName = "未订购导出" + ".xlsx";

        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();
        // 将工作簿写入输出流
        workbook.write(outputStream);
        // 关闭工作簿
        workbook.close();
        // 刷新输出流
        outputStream.flush();
        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, "", Code.OK_MSG);

    }


    /**
     * 获取已订购，已下单列表
     *
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param classTypeId
     * @param lessonType
     * @param orderId
     * @param type        1是列表，2是详情
     * @param status
     * @param orderType   1已订购，2下单，3领取，4发放
     * @return
     */
    @GetMapping("/getYetOrderSchool")
    public Result getYetOrderSchool(@RequestParam(name = "pageNum", defaultValue = "-1") Integer pageNum,
                                    @RequestParam(name = "pageSize", defaultValue = "-1") Integer pageSize,
                                    @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                    @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                    @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                    @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeId,
                                    @RequestParam(value = "lessonType", required = false, defaultValue = "1") Integer lessonType,
                                    @RequestParam(value = "orderId", required = false) Long orderId,
                                    @RequestParam(value = "type", required = false, defaultValue = "1") Integer type,
                                    @RequestParam(value = "status", required = false, defaultValue = "1") Integer status,
                                    @RequestParam(value = "orderType", required = false, defaultValue = "1") Integer orderType,
                                    @RequestParam(value = "orderSubType", required = false, defaultValue = "-1") Integer orderSubType,
                                    @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                    @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                    @RequestParam(value = "teacherName", required = false) String teacherName,
                                    @RequestParam(value = "studentName", required = false) String studentName,
                                    @RequestParam(value = "gradeId", required = false) Long gradeId,
                                    @RequestParam(value = "teacherId", required = false) Long teacherId,
                                    @RequestParam(value = "schoolId", required = false) Long schoolId,
                                    @RequestParam(value = "yearClassId", required = false) Integer yearClassId,
                                    @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                                    @RequestParam(value = "isDetails", required = false, defaultValue = "0") Integer isDetails // 0列表，1老师详情，2学员详情
    ) {

        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";

        Page<BookSchoolRs> page = new Page<>(pageNum, pageSize);

        if (orderType == 1) {
            // 已订购，未下单，按照校区显示
            iBookOrderService.getNotOrderSchoolList(page, yearPart, quarterNum, subjectsId, classTypeId, lessonType, 2, status, orderType, orderSubType, schoolIds, bookTextId, bookTextType, isDetails, teacherId, schoolId, yearClassId, teacherName, studentName, gradeId, subscribeType, lessonNum);
        } else {
            // 已下单、领取
            iBookOrderService.getYetOrderSchool(page, orderId, yearPart, quarterNum, subjectsId, classTypeId, lessonType, type, status, orderType, orderSubType, schoolIds, bookTextId, bookTextType, isDetails, teacherId, schoolId, yearClassId, teacherName, studentName, gradeId, subscribeType, lessonNum);
            if (orderType == 2 || orderSubType == 3) {
                if (!page.getRecords().isEmpty()) {
                    for (BookSchoolRs bookSchoolRs1 : page.getRecords()) {
                        bookSchoolRs1.setCount(bookSchoolRs1.getOrderCount());
                    }
                }
            }
        }

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
    }

    @GetMapping("/getYetOrderSchoolDetail")
    public Result getYetOrderSchoolDetail(@RequestParam(value = "orderId", required = false, defaultValue = "") Long orderId,
                                          @RequestParam(value = "status", required = false, defaultValue = "1") Integer status,
                                          @RequestParam(value = "orderType", required = false, defaultValue = "1") Integer orderType,
                                          @RequestParam(value = "orderSubType", required = false, defaultValue = "-1") Integer orderSubType,
                                          @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                          @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                          @RequestParam(value = "teacherName", required = false) String teacherName,
                                          @RequestParam(value = "studentName", required = false) String studentName,
                                          @RequestParam(value = "gradeId", required = false) Long gradeId,
                                          @RequestParam(value = "teacherId", required = false) Long teacherId,
                                          @RequestParam(value = "schoolId", required = false) Long schoolId,
                                          @RequestParam(value = "yearClassId", required = false) Integer yearClassId,
                                          @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                                          @RequestParam(value = "isDetails", required = false, defaultValue = "0") Integer isDetails // 0列表，1老师详情，2学员详情
    ) {

        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";

        BookOrder bookOrder = iBookOrderService.getById(orderId);

        Page<BookSchoolRs> page = new Page<>(-1, -1);
        if (orderType == 2) {
            // 下单详情
            iBookOrderService.getYetOrderSchoolDetail(page, orderId, bookOrder.getYearPart(), bookOrder.getQuarterNum(), bookOrder.getSubjectsId().toString(), bookOrder.getClassTypeId().toString(), 1, 2, status, orderType, orderSubType, schoolIds, bookTextType, lessonNum, subscribeType);
        } else {
            // 领取详情
            iBookOrderService.getYetOrderSchool(page, orderId, bookOrder.getYearPart(), bookOrder.getQuarterNum(), bookOrder.getSubjectsId().toString(), bookOrder.getClassTypeId().toString(), bookOrder.getLessonType(), 2, status, orderType, orderSubType, schoolIds, bookTextId, bookTextType, isDetails, teacherId, schoolId, yearClassId, teacherName, studentName, gradeId, subscribeType, lessonNum);
        }

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
    }

    /**
     * 获取教材发放列表
     *
     * @param orderId
     * @param status
     * @param orderType
     * @param orderSubType
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param classTypeId
     * @param disType
     * @return
     */
    @GetMapping("/getDistributeOrderSchool")
    public Result getDistributeOrderSchool(@RequestParam(value = "orderId", required = false, defaultValue = "") Long orderId,
                                           @RequestParam(value = "status", required = false, defaultValue = "1") Integer status,
                                           @RequestParam(value = "orderType", required = false, defaultValue = "1") Integer orderType,
                                           @RequestParam(value = "orderSubType", required = false, defaultValue = "-1") Integer orderSubType,
                                           @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                           @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                           @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                           @RequestParam(value = "classTypeId", required = false) String classTypeId,
                                           @RequestParam(value = "disType", required = false, defaultValue = "0") Integer disType,
                                           @RequestParam(value = "orderStatus", required = false) Integer orderStatus
    ) {
        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";
        List<BookSchoolRs> bookSchoolRs = null;
        if (disType == 0) {
            bookSchoolRs = iBookOrderService.getDistributeOrderSchool(orderId, yearPart, quarterNum, subjectsId.toString(), classTypeId.toString(), 1, 2, status, orderType, orderSubType, orderStatus, schoolIds);
        }
        return new Result(Code.OK, bookSchoolRs, "");
    }

    /**
     * 导出发放列表
     *
     * @param orderId
     * @param status
     * @param orderType
     * @param orderSubType
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param classTypeId
     * @param disType
     * @return
     */
    @GetMapping("/exportDistributeOrderSchool")
    @ApiOperation("校区发放导出")
    public Result exportDistributeOrderSchool(@RequestParam(value = "orderId", required = false, defaultValue = "") Long orderId,
                                              @RequestParam(value = "status", required = false, defaultValue = "1") Integer status,
                                              @RequestParam(value = "orderType", required = false, defaultValue = "1") Integer orderType,
                                              @RequestParam(value = "orderSubType", required = false, defaultValue = "-1") Integer orderSubType,
                                              @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                              @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                              @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                              @RequestParam(value = "classTypeId", required = false) String classTypeId,
                                              @RequestParam(value = "disType", required = false, defaultValue = "0") Integer disType,
                                              @RequestParam(value = "orderStatus", required = false, defaultValue = "0") Integer orderStatus
    ) throws IOException {
        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";
        List<BookSchoolRs> bookSchoolRs = null;
        if (disType == 0) {
            bookSchoolRs = iBookOrderService.getDistributeOrderSchool(orderId, yearPart, quarterNum, subjectsId.toString(), classTypeId.toString(), 1, 2, status, orderType, orderSubType, orderStatus, schoolIds);
        }

        // 定义年级列表
        List<String> gradeNames = Arrays.asList(
                "幼儿园", "一年级", "二年级", "三年级", "四年级", "五年级", "六年级",
                "初一", "初二", "初三", "高一", "高二", "高三"
        );

        Map<String, Map<String, Integer>> schoolGradeData = new HashMap<>();
        for (BookSchoolRs bookSchool : bookSchoolRs) {
            Map<String, Integer> gradeData = new HashMap<>();
            for (String gradeName : gradeNames) {
                gradeData.put(gradeName, null); // 默认值为0
            }
            for (BookSchoolCountRs bookSchoolCountRs : bookSchool.getBookCountList()) {
                int yearClassId = bookSchoolCountRs.getYearClassId();
                String gradeName = CommonUtil.getYearClassNameForId(yearClassId);
                if (gradeName != null) {
                    gradeData.put(gradeName, bookSchoolCountRs.getCount());
                }
            }
            schoolGradeData.put(bookSchool.getSchoolName(), gradeData);
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("订购详情");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        List<String> headList = new ArrayList<>();
        headList.add("校区");
        headList.add("科目");
        headList.add("班型");
        headList.addAll(gradeNames);
        headList.add("状态");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引
        for (BookSchoolRs bookSchool : bookSchoolRs) {
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(bookSchool.getSchoolName());
            sheet.setColumnWidth(0, 15 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(bookSchool.getSubjectsName());
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            if (bookSchool.getClassTypeId() != null) {
                Cell cell3 = row.createCell(2);
                cell3.setCellValue(bookSchool.getClassTypeName());
                sheet.setColumnWidth(2, 15 * 256);
                cell3.setCellStyle(cellStyle);
            }

            int total = 0;
            for (int i = 0; i < gradeNames.size(); i++) {
                Cell cell = row.createCell(i + 3);
                Map<String, Integer> gradeData = schoolGradeData.get(bookSchool.getSchoolName());
                Integer count = gradeData != null ? gradeData.get(gradeNames.get(i)) : null;
                if (count != null) {
                    cell.setCellValue(count);
                    total += count;
                } else {
                    cell.setCellValue("");
                }
                sheet.setColumnWidth(i + 3, 15 * 256);
                cell.setCellStyle(cellStyle);
            }

            Cell cell4 = row.createCell(gradeNames.size() + 3);
            if (bookSchool.getDisStatus() == 0) {
                cell4.setCellValue("未发完");
            } else if (bookSchool.getDisStatus() == 1) {
                cell4.setCellValue("已发完");
            }
            sheet.setColumnWidth(gradeNames.size() + 3, 15 * 256);
            cell4.setCellStyle(cellStyle);

        }
        String fileName = "校区发放列表导出" + ".xlsx";

        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();
        // 将工作簿写入输出流
        workbook.write(outputStream);
        // 关闭工作簿
        workbook.close();
        // 刷新输出流
        outputStream.flush();
        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, "", Code.OK_MSG);

    }

    /**
     * 获取教材发放数据
     *
     * @param pageNum
     * @param pageSize
     * @param orderId
     * @param orderType
     * @param orderSubType 1已发放，0未发放
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param classTypeId
     * @param yearClassId
     * @param disType      0校区发放 1教师发放 2学生发放
     * @param type         1总数计算 2列表显示
     * @param orderStatus
     * @param schoolId
     * @param teacherName
     * @param studentName
     * @param gradeId
     * @param isExport     1导出
     * @return
     * @throws IOException
     */
    @GetMapping("/getDistributeOrderSchoolDetails")
    public Result getDistributeOrderSchoolDetails(@RequestParam(name = "pageNum", defaultValue = "-1") Integer pageNum,
                                                  @RequestParam(name = "pageSize", defaultValue = "-1") Integer pageSize,
                                                  @RequestParam(value = "orderId", required = false, defaultValue = "") Long orderId,
                                                  @RequestParam(value = "orderType", required = false, defaultValue = "1") Integer orderType,
                                                  @RequestParam(value = "orderSubType", required = false) Integer orderSubType,
                                                  @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                                  @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                                  @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                                  @RequestParam(value = "classTypeId", required = false) String classTypeId,
                                                  @RequestParam(value = "yearClassId", required = false) String yearClassId,
                                                  @RequestParam(value = "disType", required = false, defaultValue = "0") Integer disType,// 0校区发放 1教师发放 2学生发放
                                                  @RequestParam(value = "type", required = false, defaultValue = "2") Integer type,// 1总数计算 2列表显示
                                                  @RequestParam(value = "orderStatus", required = false) Integer orderStatus,
                                                  @RequestParam(value = "schoolId", required = false) String schoolId,
                                                  @RequestParam(value = "teacherId", required = false) String teacherId,
                                                  @RequestParam(value = "idList", required = false) String idList,
                                                  @RequestParam(value = "teacherName", required = false) String teacherName,
                                                  @RequestParam(value = "studentName", required = false) String studentName,
                                                  @RequestParam(value = "gradeId", required = false) Long gradeId,
                                                  @RequestParam(value = "isDetails", required = false, defaultValue = "0") Integer isDetails,// 是否为详情，0否1是
                                                  @RequestParam(value = "isExport", required = false, defaultValue = "0") Integer isExport,
                                                  @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                                  @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                                  @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum

    ) throws IOException {

        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";
        Page<BookSchoolRs> page = new Page<>(pageNum, pageSize);

        iBookOrderService.getDistributeOrderSchoolDetails(page, orderId, yearPart, quarterNum, subjectsId, classTypeId, yearClassId, 1, type, orderType, orderSubType, orderStatus, disType, schoolId, teacherId, idList, teacherName, studentName, gradeId, schoolIds, isDetails, bookTextId, bookTextType, subscribeType, lessonNum);

        if (type == 1) {
            // 计数
            List<BookClassTypeCountRs> classTypeCountRs = new ArrayList<>();
            for (BookSchoolRs bookSchoolR : page.getRecords()) {
                BookClassTypeCountRs countRs = new BookClassTypeCountRs();
                countRs.setClassTypeId(String.valueOf(bookSchoolR.getClassTypeId()));
                countRs.setSubjectsId(Math.toIntExact(bookSchoolR.getSubjectsId()));
                countRs.setCount(bookSchoolR.getCount());
                classTypeCountRs.add(countRs);
            }
            return new Result(Code.GET_OK, classTypeCountRs, Code.GET_OK_MSG);
        }

        if (type == 2 && (isDetails == 0 || (isDetails == 1 && disType != 1))) {
            for (BookSchoolRs bookSchoolR : page.getRecords()) {
                bookSchoolR.setBookCountList(iBookOrderService.getGrantCountList(yearPart, quarterNum, bookSchoolR.getSchoolId(), subjectsId, String.valueOf(bookSchoolR.getClassTypeId()), yearClassId, 1, orderId, 2, orderType, orderSubType, bookSchoolR.getTeacherId(), bookSchoolR.getTeacherName(), disType, isDetails, bookTextId, bookTextType, subscribeType, lessonNum));
            }
        }

        if (isExport == 1) {
            // 导出
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("发放数据");
            CellStyle headerCellStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 14);
            headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
            headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            Row headerRow = sheet.createRow(0);
            headerRow.setHeightInPoints(20);
            sheet.createFreezePane(0, 1);
            headerCellStyle.setFont(headerFont);

            CellStyle cellStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setFontHeightInPoints((short) 11);
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setFont(font);
            cellStyle.setWrapText(true);

            List<String> headList = new ArrayList<>();

            List<String> gradeNames = Arrays.asList(
                    "幼儿园", "一年级", "二年级", "三年级", "四年级", "五年级", "六年级",
                    "初一", "初二", "初三", "高一", "高二", "高三"
            );

            if (disType == 0 && isDetails == 0) {
                headList.add("校区");
                headList.add("科目");
                headList.add("班型");
                headList.addAll(gradeNames);
                headList.add("合计");
                headList.add("状态");
            }

            if ((disType == 1 && isDetails == 0) || (disType == 0 && isDetails == 1)) {
                headList.add("教师");
                headList.add("校区");
                headList.add("科目");
                headList.add("班型");
                headList.addAll(gradeNames);
                headList.add("合计");
                headList.add("状态");
                headList.add("发放时间");
            }

            if ((disType == 2 && isDetails == 0) || (disType == 1 && isDetails == 1) || (disType == 0 && isDetails == 2)) {
                headList.add("学员姓名");
                headList.add("校区");
                headList.add("科目");
                headList.add("年级");
                headList.add("班型");
                headList.add("所属班级");
                headList.add("状态");
                headList.add("发放时间");
            }

            Map<String, Integer> subjectLessonTypeToIndexMap = new HashMap<>();
            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
                sheet.setColumnWidth(i, 20 * 256);
                subjectLessonTypeToIndexMap.put(headList.get(i), i);
            }

            String fileName = "发放列表.xlsx";

            int rowIndex = 1;// 数据行起始索引

            if (disType == 0 && isDetails == 0) {

                Map<String, Map<String, Integer>> schoolGradeData = new HashMap<>();
                for (BookSchoolRs bookSchool : page.getRecords()) {
                    Map<String, Integer> gradeData = new HashMap<>();
                    for (String gradeName : gradeNames) {
                        gradeData.put(gradeName, null); // 默认值为0
                    }
                    for (BookSchoolCountRs bookSchoolCountRs : bookSchool.getBookCountList()) {
                        int rsYearClassId = bookSchoolCountRs.getYearClassId();
                        String gradeName = CommonUtil.getYearClassNameForId(rsYearClassId);
                        if (gradeName != null) {
                            gradeData.put(gradeName, bookSchoolCountRs.getCount());
                        }
                    }
                    schoolGradeData.put(bookSchool.getSchoolName(), gradeData);
                }

                for (BookSchoolRs schoolRs : page.getRecords()) {
                    fileName = schoolRs.getBatchName() + ".xlsx";

                    Row row = sheet.createRow(rowIndex);

                    Cell cell = row.createCell(0);
                    cell.setCellValue(schoolRs.getSchoolName());
                    sheet.setColumnWidth(0, 25 * 256);
                    cell.setCellStyle(cellStyle);

                    Cell cell1 = row.createCell(1);
                    cell1.setCellValue(schoolRs.getSubjectsName());
                    sheet.setColumnWidth(1, 20 * 256);
                    cell1.setCellStyle(cellStyle);

                    Cell cell2 = row.createCell(2);
                    cell2.setCellValue(schoolRs.getClassTypeName());
                    sheet.setColumnWidth(2, 20 * 256);
                    cell2.setCellStyle(cellStyle);

                    int total = 0;
                    for (int i = 0; i < gradeNames.size(); i++) {
                        Cell cell4 = row.createCell(i + 3);
                        Map<String, Integer> gradeData = schoolGradeData.get(schoolRs.getSchoolName());
                        Integer count = gradeData != null ? gradeData.get(gradeNames.get(i)) : null;
                        if (count != null && count != 0) {
                            cell4.setCellValue(count);
                            total += count;
                        } else {
                            cell4.setCellValue("");
                        }
                        sheet.setColumnWidth(i + 3, 15 * 256);
                        cell4.setCellStyle(cellStyle);
                    }

                    Cell cell5 = row.createCell(gradeNames.size() + 3);
                    cell5.setCellValue(schoolRs.getCount());
                    sheet.setColumnWidth(gradeNames.size() + 3, 15 * 256);
                    cell5.setCellStyle(cellStyle);

                    Cell cell6 = row.createCell(gradeNames.size() + 4);
                    if (schoolRs.getInfoStatus() == 1) {
                        cell6.setCellValue("已发完");
                    } else {
                        cell6.setCellValue("未发完");
                    }
                    sheet.setColumnWidth(gradeNames.size() + 4, 15 * 256);
                    cell6.setCellStyle(cellStyle);

                    rowIndex++;
                }

            }

            if ((disType == 1 && isDetails == 0) || (disType == 0 && isDetails == 1)) {

                Map<String, Map<String, Integer>> schoolGradeData = new HashMap<>();
                for (BookSchoolRs bookSchool : page.getRecords()) {
                    Map<String, Integer> gradeData = new HashMap<>();
                    for (String gradeName : gradeNames) {
                        gradeData.put(gradeName, null); // 默认值为0
                    }
                    if (bookSchool.getBookCountList() != null) {
                        for (BookSchoolCountRs bookSchoolCountRs : bookSchool.getBookCountList()) {
                            int rsYearClassId = bookSchoolCountRs.getYearClassId();
                            String gradeName = CommonUtil.getYearClassNameForId(rsYearClassId);
                            if (gradeName != null) {
                                gradeData.put(gradeName, bookSchoolCountRs.getCount());
                            }
                        }
                    }
                    schoolGradeData.put(bookSchool.getTeacherName(), gradeData);
                }

                for (BookSchoolRs schoolRs : page.getRecords()) {
                    fileName = schoolRs.getBatchName() + ".xlsx";

                    Row row = sheet.createRow(rowIndex);

                    Cell cell = row.createCell(0);
                    cell.setCellValue(schoolRs.getTeacherName());
                    sheet.setColumnWidth(0, 20 * 256);
                    cell.setCellStyle(cellStyle);

                    Cell cell1 = row.createCell(1);
                    cell1.setCellValue(schoolRs.getSchoolName());
                    sheet.setColumnWidth(1, 25 * 256);
                    cell1.setCellStyle(cellStyle);

                    Cell cell2 = row.createCell(2);
                    cell2.setCellValue(schoolRs.getSubjectsName());
                    sheet.setColumnWidth(2, 20 * 256);
                    cell2.setCellStyle(cellStyle);

                    Cell cell3 = row.createCell(3);
                    cell3.setCellValue(schoolRs.getClassTypeName());
                    sheet.setColumnWidth(3, 20 * 256);
                    cell3.setCellStyle(cellStyle);

                    int total = 0;
                    for (int i = 0; i < gradeNames.size(); i++) {
                        Cell cell4 = row.createCell(i + 4);
                        Map<String, Integer> gradeData = schoolGradeData.get(schoolRs.getTeacherName());
                        Integer count = gradeData != null ? gradeData.get(gradeNames.get(i)) : null;
                        if (count != null && count != 0) {
                            cell4.setCellValue(count);
                            total += count;
                        } else {
                            cell4.setCellValue("");
                        }
                        sheet.setColumnWidth(i + 4, 15 * 256);
                        cell4.setCellStyle(cellStyle);
                    }

                    Cell cell5 = row.createCell(gradeNames.size() + 4);
                    cell5.setCellValue(schoolRs.getCount());
                    sheet.setColumnWidth(gradeNames.size() + 4, 15 * 256);
                    cell5.setCellStyle(cellStyle);

                    Cell cell6 = row.createCell(gradeNames.size() + 5);
                    if (schoolRs.getInfoStatus() == 1) {
                        cell6.setCellValue("已发完");
                    } else {
                        cell6.setCellValue("未发完");
                    }
                    sheet.setColumnWidth(gradeNames.size() + 5, 15 * 256);
                    cell6.setCellStyle(cellStyle);

                    Cell cell7 = row.createCell(gradeNames.size() + 6);
                    if (schoolRs.getGrantDateTime() != null) {
                        String grantDateTime = schoolRs.getGrantDateTime().toString().replace("T", " ");
                        cell7.setCellValue(grantDateTime);
                    } else {
                        cell7.setCellValue("");
                    }
                    sheet.setColumnWidth(gradeNames.size() + 6, 25 * 256);
                    cell7.setCellStyle(cellStyle);

                    rowIndex++;
                }
            }

            if ((disType == 2 && isDetails == 0) || (disType == 1 && isDetails == 1) || (disType == 0 && isDetails == 2)) {

                for (BookSchoolRs schoolRs : page.getRecords()) {
                    fileName = schoolRs.getBatchName() + ".xlsx";

                    Row row = sheet.createRow(rowIndex);

                    Cell cell = row.createCell(0);
                    cell.setCellValue(schoolRs.getStudentName());
                    sheet.setColumnWidth(0, 20 * 256);
                    cell.setCellStyle(cellStyle);

                    Cell cell1 = row.createCell(1);
                    cell1.setCellValue(schoolRs.getSchoolName());
                    sheet.setColumnWidth(1, 25 * 256);
                    cell1.setCellStyle(cellStyle);

                    Cell cell2 = row.createCell(2);
                    cell2.setCellValue(schoolRs.getSubjectsName());
                    sheet.setColumnWidth(2, 20 * 256);
                    cell2.setCellStyle(cellStyle);

                    Cell cell3 = row.createCell(3);
                    cell3.setCellValue(schoolRs.getYearClassName());
                    sheet.setColumnWidth(3, 20 * 256);
                    cell3.setCellStyle(cellStyle);

                    Cell cell4 = row.createCell(4);
                    cell4.setCellValue(schoolRs.getClassTypeName());
                    sheet.setColumnWidth(4, 20 * 256);
                    cell4.setCellStyle(cellStyle);

                    Cell cell5 = row.createCell(5);
                    cell5.setCellValue(schoolRs.getGradeName());
                    sheet.setColumnWidth(5, 30 * 256);
                    cell5.setCellStyle(cellStyle);

                    Cell cell6 = row.createCell(6);
                    if (schoolRs.getInfoStatus() != null) {
                        if (schoolRs.getInfoStatus() == 1) {
                            cell6.setCellValue("已发放");
                        } else {
                            cell6.setCellValue("未发放");
                        }
                    }

                    sheet.setColumnWidth(6, 20 * 256);
                    cell6.setCellStyle(cellStyle);

                    Cell cell7 = row.createCell(7);
                    if (schoolRs.getGrantDateTime() != null) {
                        String grantDateTime = schoolRs.getGrantDateTime().toString().replace("T", " ");
                        cell7.setCellValue(grantDateTime);
                    } else {
                        cell7.setCellValue("");
                    }
                    sheet.setColumnWidth(7, 25 * 256);
                    cell7.setCellStyle(cellStyle);

                    rowIndex++;
                }
            }

            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置为excel格式
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新输出流
            outputStream.flush();

            //关闭输出流
            outputStream.close();
        }

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
    }


    /**
     * 获取库存数据
     *
     * @param pageNum
     * @param pageSize
     * @param isDetails   0列表，1年级列表，2可发放/已发放数据，3计数，4查看导致库存的老师数据，5查看学生详情（哪个学生导致的库存）
     * @param type        0未发放，1已发放
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param classTypeId
     * @param yearClassId
     * @param schoolId
     * @param teacherName
     * @param studentName
     * @param gradeId
     * @param isExport    1导出
     * @return
     * @throws IOException
     */
    @GetMapping("/getRepertoryUnissuedList")
    public Result getRepertoryUnissuedList(@RequestParam(name = "pageNum", defaultValue = "-1") Integer pageNum,
                                           @RequestParam(name = "pageSize", defaultValue = "-1") Integer pageSize,
                                           @RequestParam(name = "isDetails", defaultValue = "0") Integer isDetails,
                                           @RequestParam(name = "type", defaultValue = "0") Integer type,
                                           @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                           @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                           @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                           @RequestParam(value = "classTypeId", required = false) String classTypeId,
                                           @RequestParam(value = "yearClassId", required = false) String yearClassId,
                                           @RequestParam(value = "schoolId", required = false) String schoolId,
                                           @RequestParam(value = "teacherId", required = false) Long teacherId,
                                           @RequestParam(value = "teacherName", required = false) String teacherName,
                                           @RequestParam(value = "studentName", required = false) String studentName,
                                           @RequestParam(value = "gradeId", required = false) Long gradeId,
                                           @RequestParam(value = "isExport", required = false, defaultValue = "0") Integer isExport,
                                           @RequestParam(value = "idList", required = false) String idList,
                                           @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                           @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                           @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum
    ) throws IOException {

        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        Page<BookSchoolRs> page = new Page<>(pageNum, pageSize);
        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";
        iBookOrderService.getRepertoryUnissuedList(page, yearPart, quarterNum, subjectsId, classTypeId, yearClassId, 1, schoolId, teacherName, studentName, gradeId, isDetails, type, idList, schoolIds, bookTextId, bookTextType, teacherId, subscribeType, lessonNum);

        if (isDetails == 0 || isDetails == 4) {
            for (BookSchoolRs bookSchoolR : page.getRecords()) {
                bookSchoolR.setBookCountList(iBookOrderService.getRepertoryUnissuedCountList(yearPart, quarterNum, subjectsId, classTypeId, yearClassId, 1, bookSchoolR.getSchoolId(), teacherName, studentName, gradeId, isDetails, type, bookTextId, bookTextType, bookSchoolR.getTeacherId(), subscribeType, lessonNum));
            }
        }

        if (isDetails == 3) {
            // 计数
            List<BookClassTypeCountRs> classTypeCountRs = new ArrayList<>();
            for (BookSchoolRs bookSchoolR : page.getRecords()) {
                BookClassTypeCountRs countRs = new BookClassTypeCountRs();
                countRs.setClassTypeId(String.valueOf(bookSchoolR.getClassTypeId()));
                countRs.setSubjectsId(Math.toIntExact(bookSchoolR.getSubjectsId()));
                countRs.setCount(bookSchoolR.getCount());
                classTypeCountRs.add(countRs);
            }
            return new Result(Code.GET_OK, classTypeCountRs, Code.GET_OK_MSG);
        }

        if (isExport == 1) {
            // 导出
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("库存数据");
            CellStyle headerCellStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 14);
            headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
            headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            Row headerRow = sheet.createRow(0);
            headerRow.setHeightInPoints(20);
            sheet.createFreezePane(0, 1);
            headerCellStyle.setFont(headerFont);

            CellStyle cellStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setFontHeightInPoints((short) 11);
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setFont(font);
            cellStyle.setWrapText(true);

            List<String> headList = new ArrayList<>();

            List<String> gradeNames = Arrays.asList(
                    "幼儿园", "一年级", "二年级", "三年级", "四年级", "五年级", "六年级",
                    "初一", "初二", "初三", "高一", "高二", "高三"
            );

            headList.add("校区");
            headList.add("科目");
            headList.add("班型");
            headList.addAll(gradeNames);
            headList.add("合计");

            Map<String, Integer> subjectLessonTypeToIndexMap = new HashMap<>();
            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
                sheet.setColumnWidth(i, 20 * 256);
                subjectLessonTypeToIndexMap.put(headList.get(i), i);
            }

            int rowIndex = 1;// 数据行起始索引

            Map<String, Map<String, Integer>> schoolGradeData = new HashMap<>();
            for (BookSchoolRs bookSchool : page.getRecords()) {
                Map<String, Integer> gradeData = new HashMap<>();
                for (String gradeName : gradeNames) {
                    gradeData.put(gradeName, null); // 默认值为0
                }
                for (BookSchoolCountRs bookSchoolCountRs : bookSchool.getBookCountList()) {
                    int rsYearClassId = bookSchoolCountRs.getYearClassId();
                    String gradeName = CommonUtil.getYearClassNameForId(rsYearClassId);
                    if (gradeName != null) {
                        gradeData.put(gradeName, bookSchoolCountRs.getCount());
                    }
                }
                schoolGradeData.put(bookSchool.getSchoolName(), gradeData);
            }

            for (BookSchoolRs schoolRs : page.getRecords()) {

                Row row = sheet.createRow(rowIndex);

                Cell cell = row.createCell(0);
                cell.setCellValue(schoolRs.getSchoolName());
                sheet.setColumnWidth(0, 25 * 256);
                cell.setCellStyle(cellStyle);

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(schoolRs.getSubjectsName());
                sheet.setColumnWidth(1, 20 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(schoolRs.getClassTypeName());
                sheet.setColumnWidth(2, 20 * 256);
                cell2.setCellStyle(cellStyle);

                for (int i = 0; i < gradeNames.size(); i++) {
                    Cell cell4 = row.createCell(i + 3);
                    Map<String, Integer> gradeData = schoolGradeData.get(schoolRs.getSchoolName());
                    Integer count = gradeData != null ? gradeData.get(gradeNames.get(i)) : null;
                    if (count != null && count != 0) {
                        cell4.setCellValue(count);
                    } else {
                        cell4.setCellValue("");
                    }
                    sheet.setColumnWidth(i + 3, 15 * 256);
                    cell4.setCellStyle(cellStyle);
                }

                Cell cell5 = row.createCell(gradeNames.size() + 3);
                cell5.setCellValue(schoolRs.getCount());
                sheet.setColumnWidth(gradeNames.size() + 3, 15 * 256);
                cell5.setCellStyle(cellStyle);

                rowIndex++;
            }


            String encodedFileName = URLEncoder.encode("库存数据.xlsx", "UTF-8");

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置为excel格式
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新输出流
            outputStream.flush();

            //关闭输出流
            outputStream.close();
        }

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
    }


    /**
     * 库存发放
     *
     * @param bookStudent
     * @return
     */
    @PostMapping("/addRepertoryUnissued")
    @RepeatSubmit(expireSeconds = 5)
    public Result addRepertoryUnissued(@RequestBody BookStudent bookStudent) {

        // 查询不符合的学生数据，作为被调整数据
        BookStudent beforeBookStudent = iBookOrderService.getNotIssued(bookStudent.getYearPart(), bookStudent.getQuarterNum(), bookStudent.getSubjectsId().toString(), bookStudent.getClassTypeId().toString(), bookStudent.getYearClassId().toString(), 1, bookStudent.getSchoolId(), bookStudent.getBookTextId());

        if (beforeBookStudent == null) {
            return new Result(Code.OK, "", "调整失败");
        }

        // 添加发放记录
        BookGrantInfo bookGrantInfo = new BookGrantInfo();
        bookGrantInfo.setYearPart(bookStudent.getYearPart());
        bookGrantInfo.setQuarterNum(bookStudent.getQuarterNum());
        bookGrantInfo.setBookStudentId(beforeBookStudent.getId());
        bookGrantInfo.setGrantId(bookStudent.getStudentId());
        bookGrantInfo.setStatus(5);
        iBookGrantInfoService.save(bookGrantInfo);

        // 添加订购学生调到其它学生记录
        BookStudentAdjust bookStudentAdjust = new BookStudentAdjust();
        bookStudentAdjust = BeanUtil.copyProperties(beforeBookStudent, BookStudentAdjust.class);
        bookStudentAdjust.setId(idWorker.nextId());
        bookStudentAdjust.setBookStudentId(beforeBookStudent.getId());
        iBookStudentAdjustService.save(bookStudentAdjust);

        // 调整原订购数据
        beforeBookStudent.setTeacherId(bookStudent.getTeacherId());
        beforeBookStudent.setGradeId(bookStudent.getGradeId());
        beforeBookStudent.setStudentId(bookStudent.getStudentId());
        beforeBookStudent.setType(2);
        beforeBookStudent.setStatus(5);
        beforeBookStudent.setGrantDateTime(LocalDateTime.now());
        beforeBookStudent.setGrantId(this.adminId);
        iBookStudentService.updateById(beforeBookStudent);

        return new Result(Code.OK, "", Code.SAVE_OK_MSG);
    }


    @GetMapping("/exportOrderSchoolDetail")
    @ApiOperation("订购详情导出")
    public Result exportOrderSchoolDetail(@RequestParam(name = "pageNum", defaultValue = "-1") Integer pageNum,
                                          @RequestParam(name = "pageSize", defaultValue = "-1") Integer pageSize,
                                          @RequestParam(value = "orderId", required = false, defaultValue = "") Long orderId,
                                          @RequestParam(value = "status", required = false, defaultValue = "1") Integer status,
                                          @RequestParam(value = "orderType", required = false, defaultValue = "1") Integer orderType,
                                          @RequestParam(value = "orderSubType", required = false, defaultValue = "-1") Integer orderSubType,
                                          @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                          @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                          @RequestParam(value = "teacherName", required = false) String teacherName,
                                          @RequestParam(value = "studentName", required = false) String studentName,
                                          @RequestParam(value = "gradeId", required = false) Long gradeId,
                                          @RequestParam(value = "teacherId", required = false) Long teacherId,
                                          @RequestParam(value = "schoolId", required = false) Long schoolId,
                                          @RequestParam(value = "yearClassId", required = false) Integer yearClassId,
                                          @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                                          @RequestParam(value = "isDetails ", required = false, defaultValue = "0") Integer isDetails // 0列表，1老师详情，2学员详情
    ) throws IOException {

        BookOrder bookOrder = iBookOrderService.getById(orderId);

        BookText bookText = iBookTextService.getById(bookOrder.getBookTextId());
        Integer subscribeType = bookText.getSubscribeType();

        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";

        Page<BookSchoolRs> page = new Page<>(pageNum, pageSize);

        if (orderType == 2) {
            //下单详情导出
            iBookOrderService.getYetOrderSchoolDetail(page, orderId, bookOrder.getYearPart(), bookOrder.getQuarterNum(), bookOrder.getSubjectsId().toString(), bookOrder.getClassTypeId().toString(), bookOrder.getLessonType(), 2, status, orderType, orderSubType, schoolIds, bookTextType, lessonNum, subscribeType);
        } else {
            iBookOrderService.getYetOrderSchool(page, orderId, bookOrder.getYearPart(), bookOrder.getQuarterNum(), bookOrder.getSubjectsId().toString(), bookOrder.getClassTypeId().toString(), bookOrder.getLessonType(), 2, status, orderType, orderSubType, schoolIds, bookTextId, bookTextType, isDetails, teacherId, schoolId, yearClassId, teacherName, studentName, gradeId, subscribeType, lessonNum);
        }


//        List<BookSchoolRs> bookSchoolRs = iBookOrderService.getYetOrderSchool(orderId,bookOrder.getYearPart(),bookOrder.getQuarterNum(),bookOrder.getSubjectsId().toString(),bookOrder.getClassTypeId().toString(),bookOrder.getLessonType(),2,status,orderType,orderSubType);
        // 定义年级列表
        List<String> gradeNames = Arrays.asList(
                "幼儿园", "一年级", "二年级", "三年级", "四年级", "五年级", "六年级",
                "初一", "初二", "初三", "高一", "高二", "高三"
        );

        Map<String, Map<String, Integer>> schoolGradeData = new HashMap<>();
        for (BookSchoolRs bookSchool : page.getRecords()) {
            Map<String, Integer> gradeData = new HashMap<>();
            for (String gradeName : gradeNames) {
                gradeData.put(gradeName, null); // 默认值为0
            }
            for (BookSchoolCountRs bookSchoolCountRs : bookSchool.getBookCountList()) {
                int rsYearClassId = bookSchoolCountRs.getYearClassId();
                String gradeName = CommonUtil.getYearClassNameForId(rsYearClassId);
                if (gradeName != null) {
                    gradeData.put(gradeName, bookSchoolCountRs.getCount());
                }
            }
            schoolGradeData.put(bookSchool.getSchoolName(), gradeData);
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("订购详情");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        List<String> headList = new ArrayList<>();
        headList.add("校区");
        headList.add("科目");
        headList.add("班型");
        headList.addAll(gradeNames);
        headList.add("合计");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引
        for (BookSchoolRs bookSchool : page.getRecords()) {
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(bookSchool.getSchoolName());
            sheet.setColumnWidth(0, 15 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(bookSchool.getSubjectsName());
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            if (bookSchool.getClassTypeId() != null) {
                Cell cell3 = row.createCell(2);
                cell3.setCellValue(bookSchool.getClassTypeName());
                sheet.setColumnWidth(2, 15 * 256);
                cell3.setCellStyle(cellStyle);
            }

            int total = 0;
            for (int i = 0; i < gradeNames.size(); i++) {
                Cell cell = row.createCell(i + 3);
                Map<String, Integer> gradeData = schoolGradeData.get(bookSchool.getSchoolName());
                Integer count = gradeData != null ? gradeData.get(gradeNames.get(i)) : null;
                if (count != null) {
                    cell.setCellValue(count);
                    total += count;
                } else {
                    cell.setCellValue("");
                }
                sheet.setColumnWidth(i + 3, 15 * 256);
                cell.setCellStyle(cellStyle);
            }

            Cell cell4 = row.createCell(gradeNames.size() + 3);
            cell4.setCellValue(bookSchool.getCount());
            sheet.setColumnWidth(gradeNames.size() + 3, 15 * 256);
            cell4.setCellStyle(cellStyle);

        }
        String fileName = "订购详情导出" + ".xlsx";

        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();
        // 将工作簿写入输出流
        workbook.write(outputStream);
        // 关闭工作簿
        workbook.close();
        // 刷新输出流
        outputStream.flush();
        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, "", Code.OK_MSG);

    }


    /**
     * 订购
     *
     * @param bookOrder
     * @return
     */
    @PostMapping("/addBookOrder")
    @RepeatSubmit(expireSeconds = 5)
    public Result addBookOrder(@RequestBody BookOrder bookOrder) {
        bookOrder.setLessonType(1);
        if (bookOrder.getBookTextId() == null) {
            return new Result(Code.ERROR, "", "请选择需要订购的教材");
        }
        //String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";
        String schoolIds = StringUtils.isNotBlank(bookOrder.getSchoolIdStr()) ? bookOrder.getSchoolIdStr() : "0";
        Page<BookSchoolRs> page = new Page<>(-1, -1);
        List<BookSchoolRs> bookSchoolRsList = iBookOrderService.getOrderSchool(page, bookOrder.getYearPart(), bookOrder.getQuarterNum(), bookOrder.getSubjectsId().toString(), bookOrder.getClassTypeId().toString(), bookOrder.getLessonType(), schoolIds, bookOrder.getBookTextId(), bookOrder.getBookTextType(), 0, null, null, null, null, null, bookOrder.getLessonNum(), null, bookOrder.getSubscribeType()).getRecords();
        if (bookSchoolRsList.size() == 0) {
            return new Result(Code.ERROR, "", "没有需要订购的学生");
        }
        bookOrder.setCreatedAt(LocalDateTime.now());
        bookOrder.setCreatedId(this.adminId);
        Integer count = iBookOrderService.addBookOrder(bookOrder, schoolIds);
        return new Result(Code.OK, "", "添加订购成功：" + count + "");
    }

    /**
     * 下单
     *
     * @param bookOrderParam
     * @return
     */
    @PostMapping("/placeOrder")
    public Result placeOrder(@RequestBody BookOrder bookOrderParam) {

        if (bookOrderParam.getBookTextId() == null) {
            return new Result(Code.ERROR, "", "请选择需要订购的教材");
        }

        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";
//        BookOrder bookOrder = iBookOrderService.getById(bookOrderParam.getId());
//        if (bookOrder == null) {
//            return new Result(Code.ERROR, "", "数据不存在");
//        }
//        if (bookOrder.getStatus() != 1) {
//            return new Result(Code.ERROR, "", "当前状态不是订购状态，操作失败，查看是否已经下单");
//        }


        QueryWrapper<BookStudent> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql(StringUtils.isBlank(bookOrderParam.getSchoolIdStr()), "school_id", schoolIds);
        queryWrapper.inSql(StringUtils.isNotBlank(bookOrderParam.getSchoolIdStr()), "school_id", bookOrderParam.getSchoolIdStr());
        queryWrapper.inSql(StringUtils.isNotBlank(bookOrderParam.getYearClassIdStr()), "year_class_id", bookOrderParam.getYearClassIdStr());
        queryWrapper.eq("class_type_id", bookOrderParam.getClassTypeId());
        queryWrapper.eq("status", 1);
        queryWrapper.eq("subjects_id", bookOrderParam.getSubjectsId());
        queryWrapper.eq("year_part", bookOrderParam.getYearPart());
        queryWrapper.eq("quarter_num", bookOrderParam.getQuarterNum());
        queryWrapper.eq("book_text_id", bookOrderParam.getBookTextId());
        queryWrapper.eq("book_text_type", bookOrderParam.getBookTextType());
        Long count = iBookStudentService.count(queryWrapper);
        if (count.equals(0L)) {
            return new Result(Code.ERROR, "", "没有需要下单的数量，请查看选中“校区与年级”是否有数量再下单");
        }

        BookText bookText = iBookTextService.getById(bookOrderParam.getBookTextId());
        Integer subscribeType = bookText.getSubscribeType();
        bookOrderParam.setSubscribeType(subscribeType);

        iBookOrderService.placeOrder(bookOrderParam, schoolIds);
        return new Result(Code.OK, "", Code.OK_MSG);
    }

    @GetMapping("/getBookCountForClassType")
    public Result getBookCountForClassType(@RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                           @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                           @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                           @RequestParam(value = "status", required = false, defaultValue = "2") Integer status,
                                           @RequestParam(value = "lessonType", required = false, defaultValue = "1") Integer lessonType,
                                           @RequestParam(value = "orderType", required = false, defaultValue = "1") Integer orderType,
                                           @RequestParam(value = "orderSubType", required = false, defaultValue = "-1") Integer orderSubType,
                                           @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                           @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                           @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum
    ) {

        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        List<BookClassTypeCountRs> bookClassTypeCountRsList = iBookOrderService.getBookCountForClassType(yearPart, quarterNum, subjectsId, lessonType, status, orderType, orderSubType, bookTextId, bookTextType, subscribeType, lessonNum);
        return new Result(Code.OK, bookClassTypeCountRsList, Code.OK_MSG);
    }

    @GetMapping("/getBatchName")
    public Result getBatchName(@RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                               @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                               @RequestParam(value = "subjectsId", required = false) Long subjectsId,
                               @RequestParam(value = "classTypeId", required = false) Long classTypeId,
                               @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                               @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                               @RequestParam(value = "bookTextId", required = false) Long bookTextId) {

        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        String batchName = iBookOrderService.getBatchName(yearPart, quarterNum, subjectsId, classTypeId, bookTextType, bookTextId, lessonNum, subscribeType);
        Map<String, Object> map = new HashMap<>();
        map.put("batchName", batchName);

        return new Result(Code.OK, map, Code.OK_MSG);
    }


    /**
     * 获取批次
     *
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @GetMapping("/getBatchNameList")
    public Result getBatchNameList(@RequestParam(value = "yearPart", required = false, defaultValue = "") String yearPart,
                                   @RequestParam(value = "quarterNum", required = false, defaultValue = "") String quarterNum,
                                   @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                   @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                   @RequestParam(value = "classTypeId", required = false) String classTypeId,
                                   @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                                   @RequestParam(value = "bookTextId", required = false) String bookTextId
    ) {

        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        //String batchName = iBookOrderService.getBatchName(yearPart,quarterNum,subjectsId,classTypeId);
        QueryWrapper<BookOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(bookTextId), "book_text_id", bookTextId);
        queryWrapper.eq("book_text_type", bookTextType);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(classTypeId), "class_type_id", classTypeId);
        if (subscribeType == 1) {
            queryWrapper.eq("lesson_num", lessonNum);
        }
        queryWrapper.eq("book_text_type", bookTextType);
        //根据batch_num排序升序
        queryWrapper.orderByAsc("batch_num");
        List<BookOrder> bookOrderList = iBookOrderService.list(queryWrapper);


        return new Result(Code.OK, bookOrderList, Code.OK_MSG);
    }

    /**
     * 未下单（已订购）数量
     *
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param classTypeId
     * @param lessonType
     * @return
     */
    @GetMapping("/getNotOrderSchoolCountForClassType")
    public Result getNotOrderSchoolCountForClassType(@RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                                     @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                                     @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                                     @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeId,
                                                     @RequestParam(value = "lessonType", required = false, defaultValue = "1") Integer lessonType,
                                                     @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                                     @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                                                     @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType
    ) {

        BookText bookText = iBookTextService.getById(bookTextId);
        Integer subscribeType = bookText.getSubscribeType();

        List<BookClassTypeCountRs> bookClassTypeCountRsList = iBookOrderService.getNotOrderSchoolCountForClassType(yearPart, quarterNum, subjectsId, classTypeId, lessonType, bookTextId, bookTextType, lessonNum, subscribeType);

        return new Result(Code.OK, bookClassTypeCountRsList, Code.OK_MSG);
    }

    /**
     * 获取取消订购列表
     */
    @GetMapping("/getCancelOrderList")
    public Result getCancelOrderList(@RequestParam(name = "pageNum", defaultValue = "-1") Integer pageNum,
                                     @RequestParam(name = "pageSize", defaultValue = "-1") Integer pageSize,
                                     @RequestParam(value = "yearPart", required = false, defaultValue = "") Integer yearPart,
                                     @RequestParam(value = "quarterNum", required = false, defaultValue = "") Integer quarterNum,
                                     @RequestParam(value = "subjectsId", required = false, defaultValue = "") String subjectsId,
                                     @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeId,
                                     @RequestParam(value = "bookTextType", required = false, defaultValue = "1") Integer bookTextType,
                                     @RequestParam(value = "lessonType", required = false, defaultValue = "1") Integer lessonType,
                                     @RequestParam(value = "bookTextId", required = false) Long bookTextId,
                                     @RequestParam(value = "teacherName", required = false) String teacherName,
                                     @RequestParam(value = "studentName", required = false) String studentName,
                                     @RequestParam(value = "teacherId", required = false) Long teacherId,
                                     @RequestParam(value = "schoolId", required = false) Long schoolId,
                                     @RequestParam(value = "gradeId", required = false) Long gradeId,
                                     @RequestParam(value = "yearClassId", required = false) Integer yearClassId,
                                     @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
                                     @RequestParam(value = "isExport", required = false, defaultValue = "0") Integer isExport, // 是否为导出，0否1是
                                     @RequestParam(value = "type", required = false, defaultValue = "1") Integer type,// 1列表显示 2合计
                                     @RequestParam(value = "isDetails", required = false, defaultValue = "0") Integer isDetails // 0列表，1老师详情，2学员详情
    ) throws IOException {

        Page<BookSchoolRs> page = new Page<>(pageNum, pageSize);
        String schoolIds = StringUtils.isNotBlank(this.baseSchoolIdStr) ? this.baseSchoolIdStr : "0";

        iBookOrderService.getCancelOrderList(page, yearPart, quarterNum, subjectsId, classTypeId, lessonType, schoolIds, bookTextId, bookTextType, isDetails, teacherId, schoolId, yearClassId, teacherName, studentName, gradeId, lessonNum, type);

        if (type == 2) {
            // 计数
            List<BookClassTypeCountRs> classTypeCountRs = new ArrayList<>();
            for (BookSchoolRs bookSchoolR : page.getRecords()) {
                BookClassTypeCountRs countRs = new BookClassTypeCountRs();
                countRs.setClassTypeId(String.valueOf(bookSchoolR.getClassTypeId()));
                countRs.setSubjectsId(Math.toIntExact(bookSchoolR.getSubjectsId()));
                countRs.setCount(bookSchoolR.getCount());
                classTypeCountRs.add(countRs);
            }
            return new Result(Code.GET_OK, classTypeCountRs, Code.GET_OK_MSG);
        }

        if (type == 1 && isDetails != 2) {
            for (BookSchoolRs bookSchoolR : page.getRecords()) {
                bookSchoolR.setBookCountList(iBookOrderService.getCancelOrderCountList(yearPart, quarterNum, subjectsId, classTypeId, lessonType, schoolIds, bookTextId, bookTextType, isDetails, bookSchoolR.getSchoolId(), bookSchoolR.getTeacherId(), yearClassId, lessonNum));
            }
        }

        if (isExport == 1) {
            // 导出
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("发放数据");
            CellStyle headerCellStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 14);
            headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
            headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            Row headerRow = sheet.createRow(0);
            headerRow.setHeightInPoints(20);
            sheet.createFreezePane(0, 1);
            headerCellStyle.setFont(headerFont);

            CellStyle cellStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setFontHeightInPoints((short) 11);
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setFont(font);
            cellStyle.setWrapText(true);

            List<String> headList = new ArrayList<>();

            List<String> gradeNames = Arrays.asList("幼儿园", "一年级", "二年级", "三年级", "四年级", "五年级", "六年级", "初一", "初二", "初三", "高一", "高二", "高三");

            headList.add("校区");
            headList.add("科目");
            headList.add("班型");
            headList.addAll(gradeNames);
            headList.add("合计");

            Map<String, Integer> subjectLessonTypeToIndexMap = new HashMap<>();
            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
                sheet.setColumnWidth(i, 20 * 256);
                subjectLessonTypeToIndexMap.put(headList.get(i), i);
            }

            String fileName = "取消列表.xlsx";

            int rowIndex = 1;// 数据行起始索引

            Map<String, Map<String, Integer>> schoolGradeData = new HashMap<>();
            for (BookSchoolRs bookSchool : page.getRecords()) {
                Map<String, Integer> gradeData = new HashMap<>();
                for (String gradeName : gradeNames) {
                    gradeData.put(gradeName, null); // 默认值为0
                }
                for (BookSchoolCountRs bookSchoolCountRs : bookSchool.getBookCountList()) {
                    int rsYearClassId = bookSchoolCountRs.getYearClassId();
                    String gradeName = CommonUtil.getYearClassNameForId(rsYearClassId);
                    if (gradeName != null) {
                        gradeData.put(gradeName, bookSchoolCountRs.getCount());
                    }
                }
                schoolGradeData.put(bookSchool.getSchoolName(), gradeData);
            }

            for (BookSchoolRs schoolRs : page.getRecords()) {

                Row row = sheet.createRow(rowIndex);

                Cell cell = row.createCell(0);
                cell.setCellValue(schoolRs.getSchoolName());
                sheet.setColumnWidth(0, 25 * 256);
                cell.setCellStyle(cellStyle);

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(schoolRs.getSubjectsName());
                sheet.setColumnWidth(1, 20 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(schoolRs.getClassTypeName());
                sheet.setColumnWidth(2, 20 * 256);
                cell2.setCellStyle(cellStyle);

                int total = 0;
                for (int i = 0; i < gradeNames.size(); i++) {
                    Cell cell4 = row.createCell(i + 3);
                    Map<String, Integer> gradeData = schoolGradeData.get(schoolRs.getSchoolName());
                    Integer count = gradeData != null ? gradeData.get(gradeNames.get(i)) : null;
                    if (count != null && count != 0) {
                        cell4.setCellValue(count);
                        total += count;
                    } else {
                        cell4.setCellValue("");
                    }
                    sheet.setColumnWidth(i + 3, 15 * 256);
                    cell4.setCellStyle(cellStyle);
                }

                Cell cell5 = row.createCell(gradeNames.size() + 3);
                cell5.setCellValue(schoolRs.getCount());
                sheet.setColumnWidth(gradeNames.size() + 3, 15 * 256);
                cell5.setCellStyle(cellStyle);

                rowIndex++;
            }

            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置为excel格式
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新输出流
            outputStream.flush();

            //关闭输出流
            outputStream.close();
        }

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
    }


}
